//
//  MainViewController.m
//  ZZGallerySliderViewDemo
//
//  Created by chester on 14-7-28.
//  Copyright (c) 2014年 zhangzhi. All rights reserved.
//

#import "MainViewController.h"
#import "Header.h"
#import "ZZGallerySliderLayout.h"
#import "ZZGallerySliderCell.h"
#import "DetailsViewController.h"
#import "DownLoadDataHelper.h"
#import "DishesMadels.h"
#import "UIImageView+WebCache.h"
@interface MainViewController ()<sendDataDelegate>
{
    UICollectionView *galleryCollectionView;
    NSMutableArray *dataArray;
    NSString *urlStr;
    DownLoadDataHelper *down;
    NSString  *NowStr;
    NSInteger number;
    //NSString *str;
    NSInteger Max;
}

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationItem.title = self.str;
    [self initData];
   // [self initCollectionView];
    //
    down = [[DownLoadDataHelper alloc] init];
    down.sendDataDelegete = self;
    //self.str = @"早餐";
    urlStr = [NSString stringWithFormat:@"http://apis.juhe.cn/cook/query?key=2392dbacea9127e5beb16b0758c3fcaa&menu=%@&rn=10&pn=1",self.str];
    // ios 9转码
    NowStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    number = 1;
    [down downLoadDataWithUrlString:NowStr];
    //self.alldataArray = [NSMutableArray array];

}
-(NSMutableArray *)alldataArray
{
    if (!_alldataArray) {
        self.alldataArray = [NSMutableArray array];
    }
    return _alldataArray;
}

- (void)sendDataBack:(NSData *)data isRequest:(BOOL)isRequest
{
    if (isRequest) {
        
        NSDictionary *allDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        if ([[allDic objectForKey:@"resultcode"]  isEqual: @"202"]) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"无效的搜索结果" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:alert animated:YES completion:nil];
          UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
              
              [self.navigationController popViewControllerAnimated:NO];
          }];
            [alert addAction:action];
            return;

        }
        NSDictionary *towDic = [allDic objectForKey:@"result"];
        NSArray *allArray = [towDic objectForKey:@"data"];
        for (NSDictionary *dic in allArray) {
            DishesMadels *dishes = [[DishesMadels alloc] init];
            [dishes setValuesForKeysWithDictionary:dic];
            [self.alldataArray addObject:dishes];
        }
        [self initCollectionView];
        [galleryCollectionView reloadData];
    }else{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络连接失败" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alert animated:YES completion:nil];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction *  action) {
            [self dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popToRootViewControllerAnimated:YES];
        }];
        [alert addAction:action ];

    }
    
}
//- (NSMutableArray *)alldataArray
//{
//    if (!_alldataArray) {
//        self.alldataArray = [NSMutableArray array];
//    }
//    return _alldataArray;
//}


- (void)dragUp
{
    number = (number++) * 10 + 1;
    NSString *string = [NSString stringWithFormat:@"%ld",number];
    urlStr = [NSString stringWithFormat:@"http://apis.juhe.cn/cook/query?key=2392dbacea9127e5beb16b0758c3fcaa&menu=%@&rn=10&pn=%@",self.str,string];
    // ios 9转码
    NowStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [down downLoadDataWithUrlString:NowStr];
    [galleryCollectionView footerEndRefreshing];
    
}


-(void)initData
{
    dataArray = [NSMutableArray array];
    for (int i=0; i<self.alldataArray.count; i++) {
        [dataArray addObject:@"messages_bg_2@2x"];
    }
}

-(void)initCollectionView
{
    ZZGallerySliderLayout *layout = [[ZZGallerySliderLayout alloc] init];
    [layout setContentSize:self.alldataArray.count];
    galleryCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, CELL_WIDTH, CGRectGetHeight([UIScreen mainScreen].bounds)) collectionViewLayout:layout];
    [galleryCollectionView registerClass:[ZZGallerySliderCell class] forCellWithReuseIdentifier:@"CELL"];
    galleryCollectionView.delegate = self;
    galleryCollectionView.dataSource = self;
    galleryCollectionView.backgroundColor = [UIColor clearColor];
    //添加上拉加载
    [galleryCollectionView addFooterWithTarget:self action:@selector(dragUp)];
    galleryCollectionView.userInteractionEnabled = YES;


    //最下面的图片
    UIImageView *bottomView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 60+170*self.alldataArray.count+[UIScreen mainScreen].bounds.size.height- DRAG_INTERVAL-430, CELL_WIDTH, 400)];
    bottomView.backgroundColor = [UIColor blackColor];
   // [galleryCollectionView addSubview:bottomView];
    
    UIImageView *backGroundImage = [[UIImageView alloc] initWithFrame:galleryCollectionView.frame];
    backGroundImage.image = [UIImage imageNamed:@"qqq"];
    backGroundImage.userInteractionEnabled = YES;
    [self.view addSubview:backGroundImage];
    
    [backGroundImage addSubview:galleryCollectionView];
}

#pragma -mark UICollectionView 代理方法

-(NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.alldataArray.count+1;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return CGSizeMake(CELL_WIDTH, HEADER_HEIGHT);
    }else if(indexPath.row == 1){
        return CGSizeMake(CELL_WIDTH, CELL_CURRHEIGHT);
    }else{
        return CGSizeMake(CELL_WIDTH, CELL_HEIGHT);
    }
}

-(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation
{
    return UIInterfaceOrientationIsLandscape(toInterfaceOrientation);
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ZZGallerySliderCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"CELL" forIndexPath:indexPath];
    cell.delegate = self;
    cell.tag = indexPath.row;
    [cell setIndex:indexPath.row];
    [cell reset];
    
    if(indexPath.row == 0){
        cell.imageView.image = [UIImage imageNamed:@"labelImage.jpg"];
    }else{
        if(indexPath.row == 1){
            [cell revisePositionAtFirstCell];
        }
        //
        NSDictionary *item = [self.alldataArray objectAtIndex:indexPath.row - 1];
        NSString *playerName = [item valueForKey:@"title"];
        NSString *ingredients = [item valueForKey:@"ingredients"];
        UILabel *nameLabel = (UILabel*)[cell viewWithTag:101];
        nameLabel.font = [UIFont systemFontOfSize:14];
        nameLabel.numberOfLines = 0;
        [nameLabel setText:playerName];
        
        UIView *borderView = [cell viewWithTag:102];
        borderView.layer.borderWidth = 1;
        NSString *imgURL = [[item valueForKey:@"albums"] lastObject];
    
       // UIImageView *imgView = (UIImageView*)[cell viewWithTag:100];
        //[imgView setImage:nil];
        
        
        //imgView.image = [UIImage imageNamed:imgURL];
        [cell.headImageView sd_setImageWithURL:[NSURL URLWithString:imgURL] placeholderImage:[UIImage imageNamed:@"1"]];
        //
        //cell.headImageView.image = [UIImage imageNamed:@"烘培.jpeg"];
        [cell setNameLabel:playerName];
        [cell setDescLabel:ingredients];
        if (indexPath.row%2 == 0) {
        
            UIImage *image = [UIImage imageNamed:@"cellBack.jpg"];
            cell.imageView.image = image;
        }else {
            UIImage *image = [UIImage imageNamed:@"cellBack1.jpg"];
            cell.imageView.image = image;
        }
    }
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        
    }else {
        
        CGRect cellFramInSuperView = [collectionView convertRect:[collectionView cellForItemAtIndexPath:indexPath].frame toView:[collectionView superview]];
        DetailsViewController *details = [[DetailsViewController alloc] init];
        details.dish = self.alldataArray[indexPath.row - 1];
        details.yOrigin = cellFramInSuperView.origin.y - 60;
        
        //NSLog(@"%f",cellFramInSuperView.origin.y - 60);
        
        [self.navigationController pushViewController:details animated:NO];
        [collectionView deselectItemAtIndexPath:indexPath animated:YES];
        //NSLog(@"%ld",indexPath.row);
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
